/*
 * Copyright 2009 BioTeam Inc
 * 
 * Licensed under License GNU LESSER GENERAL PUBLIC LICENSE version 3.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.gnu.org/copyleft/lesser.html
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package net.bioteam.appweb.ds;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class DSPersister
{

	public static String SUB_FILE = "d:/tmp/sub.bean";

	public static Map<String, Subscription> loadSubscription() throws Exception
	{
		//Map<String, Subscription> subs = new HashMap<String, Subscription>();
		File file = new File(SUB_FILE);
		if (!file.exists())
		{
			return new HashMap<String, Subscription>();
		}
			
		XMLDecoder d = new XMLDecoder(new BufferedInputStream(new FileInputStream(SUB_FILE)));
		Map<String, Subscription> outMap = (Map<String, Subscription>) d.readObject();
		d.close();
		return outMap;
		

	}

	public static void writeSubscription(Map<String, Subscription> subs) throws Exception
	{
		XMLEncoder e = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(SUB_FILE)));
		e.writeObject(subs);
		e.close();
	}
	
	public static Subscription toSubscription(SrcDataset ds)
	{
		Subscription sub=new Subscription();
		sub.setName(ds.getName());
		sub.setType(ds.getType());
		sub.setFilename(ds.getFilename());
		sub.setLocalds(false);
		sub.setCreated(new Date());
		sub.setServerId(ds.getId());
		sub.setEnabled(true);
		sub.setLocalds(false);
		return sub;
	}

	public static void reSub(Collection<SrcDataset> dss) throws Exception
	{
		Map<String, Subscription> subs = loadSubscription();
		Set<String> subkeys = new HashSet<String>();
		subkeys.addAll(subs.keySet());
		Set<String> newkeys = new HashSet<String>();
		for (SrcDataset ds : dss)
		{
			if (!subs.containsKey(ds.getName()))
			{
				subs.put(ds.getName(), toSubscription(ds));

			}
			newkeys.add(ds.getName());
		}
		subkeys.removeAll(newkeys);
		for (String key : subkeys)
		{
			subs.remove(key);
		}
		writeSubscription(subs);
	}
}
